package com.sam.demo.spring.boot.jpa.config;

import com.alibaba.druid.pool.xa.DruidXADataSource;
import com.atomikos.jdbc.AtomikosDataSourceBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;

import java.util.Properties;

public class JpaConfigCommon {
    private String url;
    private String username;
    private String password;

    @Autowired
    private JpaVendorAdapter jpaVendorAdapter;

    public AtomikosDataSourceBean dataSource(String uniqueResourceName) {
        DruidXADataSource mysqlXaDataSource = new DruidXADataSource();
        mysqlXaDataSource.setUrl(url);
        mysqlXaDataSource.setUsername(username);
        mysqlXaDataSource.setPassword(password);

        AtomikosDataSourceBean xaDataSource = new AtomikosDataSourceBean();
        xaDataSource.setXaDataSource(mysqlXaDataSource);
        xaDataSource.setMinPoolSize(5);
        xaDataSource.setPoolSize(5);
        xaDataSource.setMaxPoolSize(30);
        xaDataSource.setBorrowConnectionTimeout(60);
        xaDataSource.setReapTimeout(20);
        xaDataSource.setMaxIdleTime(60);
        xaDataSource.setMaintenanceInterval(60);
        xaDataSource.setUniqueResourceName(uniqueResourceName);
        return xaDataSource;
    }

    public LocalContainerEntityManagerFactoryBean entityManagerFactory(String uniqueResourceName, String packagesToScan) {
        Properties properties = new Properties();
        properties.put("hibernate.transaction.jta.platform", AtomikosJtaPlatfom.class.getName());
        properties.put("javax.persistence.transactionType", "JTA");

        LocalContainerEntityManagerFactoryBean entityManager = new LocalContainerEntityManagerFactoryBean();
        entityManager.setJpaVendorAdapter(jpaVendorAdapter);
        entityManager.setPackagesToScan(packagesToScan);
        entityManager.setJtaDataSource(dataSource(uniqueResourceName));
        entityManager.setJpaProperties(properties);
        return entityManager;

    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
